<script setup lang="ts">
import type { ColumnItem } from 'wot-design-uni/components/wd-picker-view/types'
import { storeToRefs } from 'pinia'
import { computed, onMounted, ref } from 'vue'

const props = withDefaults(
  defineProps<{
    modelValue: any
    alignRight?: boolean
    dictKey: string
    placeholder?: string
    disabled?: boolean
    readonly?: boolean
  }>(),
  {
    disabled: false,
    readonly: false,
  },
)

const emit = defineEmits(['update:modelValue'])

const dictStore = useDictStore()
const { dictMap } = storeToRefs(dictStore)

onMounted(() => {
  if (props.dictKey && !dictMap.value[props.dictKey]) {
    dictStore.getDict(props.dictKey)
  }
})

const columns = computed<ColumnItem[]>(() => {
  return (dictMap.value[props.dictKey] || []).map(item => ({
    label: item.name,
    value: item.value,
    disabled: item.disabled === 1,
  }))
})

const showPicker = ref(false)

const pickerValue = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

function openPicker() {
  if (!props.readonly) {
    showPicker.value = true
  }
}
</script>

<template>
  <view @click="openPicker">
    <wd-picker
      v-model="pickerValue"
      v-model:visible="showPicker"
      :align-right="props.alignRight"
      :columns="columns"
      :disabled="props.disabled"
      :readonly="props.readonly"
      :placeholder="props.placeholder || '请选择'"
    />
  </view>
</template>

<style lang="scss" scoped>
.dict-picker {

}
</style>
